package com.best4cloud.auth.security.password;

import com.best4cloud.auth.service.BestUserDetailsService;
import com.best4cloud.common.core.security.SecurityUtils;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

@Component
public class PasswordAuthenticationProvider implements AuthenticationProvider {

    private final BestUserDetailsService userDetailsService;

    public PasswordAuthenticationProvider(BestUserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        PasswordAuthenticationToken authenticationToken = (PasswordAuthenticationToken) authentication;
        String username = (String) authenticationToken.getPrincipal();
        String password = (String) authenticationToken.getCredentials();
        UserDetails user = userDetailsService.loadUserByUsername(username);
        if (user == null || !SecurityUtils.matchesPassword(password, user.getPassword())) {
            throw new InternalAuthenticationServiceException("账户名或密码错误！");
        }
        PasswordAuthenticationToken authenticationResult = new PasswordAuthenticationToken(username, user.getAuthorities());
        authenticationResult.setDetails(authenticationToken.getDetails());
        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return PasswordAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
